global class CopyApplicationFields
{
    Webservice static string CloneFields()
    {
        Health_Card_Renewal_Form__c App = new Health_Card_Renewal_Form__c();
        
        Schema.DescribeSObjectResult fieldResult = App.getSObjectType().getDescribe();
        
        List<Schema.SObjectField> ple = fieldResult.fields.getMap().values();
        
        List<Field_Master__c> Field_Master_Records = new List<Field_Master__c>();
        
        List<Field_Master__c> FML = [SELECT id, API_Name__c FROM Field_Master__c];
        
        Boolean flag = true;
        for (Schema.SObjectField f : ple) 
        {
            flag = true;
            
            for(Field_Master__c FM_trav : FML)
            {
                if(FM_trav.API_Name__c == f.getDescribe().getName())
                {
                    flag = false;
                    break;
                }
            }
            if(flag)
            {
                if(String.ValueOf(f.getDescribe().getReferenceTo()) != '()')
                {
                    Field_Master_Records.Add(new Field_Master__c(Referencing_Value__c = 'eFormCode__c', Reference_To__c = String.ValueOf(f.getDescribe().getReferenceTo()), name = f.getDescribe().getLabel(), API_Name__c = f.getDescribe().getName()));
                }
                else
                {
                    Field_Master_Records.Add(new Field_Master__c(Referencing_Value__c = '', Reference_To__c = String.ValueOf(f.getDescribe().getReferenceTo()), name = f.getDescribe().getLabel(), API_Name__c = f.getDescribe().getName()));                
                }
            }
        }
        
        try
        {
            Field_Master__c fm = new Field_Master__c();
            
            Schema.SObjectField external_field_name;
            
            Schema.DescribeSObjectResult fm_fields = fm.getSObjectType().getDescribe();
            
            List<Schema.SObjectField> Fields = fm_fields.fields.getMap().values();
            
            for(Schema.SObjectField f : Fields)
            {
                if(f.getDescribe().isExternalID())
                {
                    external_field_name = f;
                }
            }
            
            Database.upsert(Field_Master_Records, external_field_name);
            
            return 'Success';
        }
        catch(System.Exception et)
        {
            return String.ValueOf(et);
        }
    }
}